﻿using System;
using System.Collections.Generic;
using System.Windows.Markup;
using VsxFactory.Modeling.VisualStudio;
using Microsoft.VisualStudio.Modeling;
using System.Linq;
using VsxFactory.Modeling.Strategies.Rules;

namespace VsxFactory.Modeling.Strategies
{
    [ContentProperty("Strategies")]
    public class AggregateStrategy : IGenerationStrategy, ISupportsGenerateCommand
    {
        public List<IStrategy> Strategies { get; protected set; }
        private IVsProject projectNode;
        public Func<IStrategyContext, ModelElement, GenerationSpec> CreateGenerationSpec {get;set;}

        public AggregateStrategy()
        {
            Strategies = new List<IStrategy>();
        }

        public virtual bool Initialize(IStrategiesHost host, IServiceProvider serviceProvider, IVsProjectFileItem node)
        {
            if (Strategies.Count > 0)
            {
                projectNode = node.Project;
                if (CreateGenerationSpec == null)
                    CreateGenerationSpec = (ctx, mel) => new GenerationSpec(mel, projectNode, Guid.Empty);

                foreach (var s in Strategies)
                {
                    if (s is IGenerationStrategy)
                    {
                        var gs = s as IGenerationStrategy;
                    if (gs.CreateGenerationSpec == null)
                        gs.CreateGenerationSpec = this.CreateGenerationSpec;
                    gs.Initialize(host, serviceProvider, node);
                    }
                    if (s is IProjectGenerationStrategy && serviceProvider is Store)
                    {
                        var ps = s as IProjectGenerationStrategy;
                        ps.Initialize(host, serviceProvider as Store);
                    }
                };
                //System.Xaml.XamlServices.
                return true;
            }
            return false;
        }

        void IGenerationStrategy.OnDocumentSaved(IVsProjectFileItem document)
        {
            foreach(var s in Strategies.OfType<IGenerationStrategy>())
                s.OnDocumentSaved(document);
        }

        bool IGenerationStrategy.OnDocumentClosed(IVsProjectFileItem document)
        {
            bool flag = false;
            foreach(var s in Strategies.OfType<IGenerationStrategy>())
                flag |= s.OnDocumentClosed(document);
            return flag;
        }

        void IGenerationStrategy.GenerateArtifacts(IVsProjectFileItem document)
        {
            foreach(var p in Strategies.OfType<IProjectGenerationStrategy>())
                p.GenerateProjects();
            foreach(var s in Strategies.OfType<IGenerationStrategy>())
                s.GenerateArtifacts(document);
        }

        public virtual bool CanExecuteGenerateCommand(IVsProjectItem item)
        {
            return false;
        }
    }
}
